package com.guoj.easyweb.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guoj.easyweb.common.utils.EncryptUtil;
import com.guoj.easyweb.common.utils.LayTableEntity;
import com.guoj.easyweb.common.utils.ResponseEntity;
import com.guoj.easyweb.common.utils.StatusCode;
import com.guoj.easyweb.entity.TbUser;
import com.guoj.easyweb.service.ITbUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author guoj
 * @since 2019-06-20
 */
@Controller
@RequestMapping("/user")
public class TbUserController {

	@Autowired
	private ITbUserService userService;

	/**
	 * 用户列表，分页。
	 * -- pageNum和pageSize是前端根据layui.table规范自定义的名称
	 * @return
	 */
	@RequestMapping(value = "/userList")
	@ResponseBody
	public LayTableEntity userList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "pageSize") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "create_time") String sort,
			@RequestParam(value = "order", defaultValue = "desc") String order) {
		System.out.println("====================分页参数======================");
		System.out.println("当前页：" + pageNum);
		System.out.println("每页显示条数：" + pageSize);
		System.out.println("排序字段：" + generateFieldToColumn(sort));
		System.out.println("排序规则：" + order);
		System.out.println("====================分页参数======================");
		Page<TbUser> page = new Page<>(pageNum, pageSize);
		QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.isNotNull("id");
		// 前端是否点击了表格排序三角
		if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
			if (StringUtils.equals("asc", order))
				queryWrapper.orderByAsc(generateFieldToColumn(sort));
			else
				queryWrapper.orderByDesc(generateFieldToColumn(sort));
		}
		IPage<TbUser> userList = userService.getBaseMapper().selectPage(page, queryWrapper);
		return new LayTableEntity(StatusCode.LAYUI_OK, "获取用户列表成功", userList.getTotal(), userList.getRecords());
	}

	/**
	 * 把字段转换为表中的列名
	 * @param field
	 * @return
	 */
	public String generateFieldToColumn(String field) {
		if (StringUtils.equals("createTime", field))
			return "create_time";
		else if (StringUtils.equals("headerImg", field))
			return "header_img";
		else
			return field;
	}


	/**
	 * 用户列表-搜索，分页。
	 * -- pageNum、pageSize、username、nickname、sex是前端根据table.reload的where条件对应的
	 * @return
	 */
	@RequestMapping(value = "/userListSearch")
	@ResponseBody
	public LayTableEntity userListSearch(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "pageSize") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "create_time") String sort,
			@RequestParam(value = "order", defaultValue = "desc") String order,
			@RequestParam(value = "username") String username,
			@RequestParam(value = "nickname") String nickname,
			@RequestParam(value = "sex") Integer sex) {
		System.out.println("====================分页搜索参数======================");
		System.out.println("当前页：" + pageNum);
		System.out.println("每页显示条数：" + pageSize);
		System.out.println("排序字段：" + generateFieldToColumn(sort));
		System.out.println("排序规则：" + order);
		System.out.println("账号：" + username);
		System.out.println("昵称：" + nickname);
		System.out.println("性别：" + sex);
		System.out.println("====================分页搜索参数======================");
		// 分页
		Page<TbUser> page = new Page<>(pageNum, pageSize);
		// 条件
		QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.isNotNull("id");
		// 前端是否点击了表格排序三角
		if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
			if (StringUtils.equals("asc", order))
				queryWrapper.orderByAsc(generateFieldToColumn(sort));
			else
				queryWrapper.orderByDesc(generateFieldToColumn(sort));
		}
		// 搜索了哪些条件
		if (StringUtils.isNotBlank(username)) {
			queryWrapper.like("username", username);
		}
		if (StringUtils.isNotBlank(nickname)) {
			queryWrapper.like("nickname", nickname);
		}
		if (sex != null) {
			queryWrapper.eq("sex", sex);
		}

		IPage<TbUser> userListSearch = userService.getBaseMapper().selectPage(page, queryWrapper);
		return new LayTableEntity(StatusCode.LAYUI_OK, "获取用户列表成功", userListSearch.getTotal(), userListSearch.getRecords());
	}

	/**
	 * 添加用户
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/addUser")
	@ResponseBody
	public ResponseEntity addUser(TbUser user) {
		System.out.println("################ user: " + user);
		if (user == null) {
			return new ResponseEntity(false, StatusCode.ERROR, "要添加的用户信息为空！");
		}
		int result = userService.addUser(user);
		if (result == 0) {
			return new ResponseEntity(false, StatusCode.ERROR, "添加用户失败！");
		}
		return new ResponseEntity(true, StatusCode.OK, "添加用户成功！");
	}

	/**
	 * 修改用户
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/editUser")
	@ResponseBody
	public ResponseEntity editUser(TbUser user) {
		System.out.println("################ user: " + user);
		if (user == null) {
			return new ResponseEntity(false, StatusCode.ERROR, "要修改的用户信息为空！");
		}
		boolean result = userService.updateById(user);
		if (!result) {
			return new ResponseEntity(false, StatusCode.ERROR, "修改用户失败！");
		}
		return new ResponseEntity(true, StatusCode.OK, "修改用户成功！");
	}

	/**
	 * 修改用户状态：启用/禁用
	 * @param id
	 * @param flag
	 * @return
	 */
	@RequestMapping(value = "/switchStatus")
	@ResponseBody
	public ResponseEntity switchStatus(@RequestParam(value = "id", defaultValue = "0") long id,
			@RequestParam(value = "flag", defaultValue = "0") Integer flag) {
		System.out.println("============switch启用/禁用============");
		System.out.println(id);
		System.out.println(flag);
		System.out.println("============switch启用/禁用============");
		TbUser user = new TbUser();
		user.setId(id);
		user.setFlag(flag);
		boolean result = userService.updateById(user);
		if (!result) {
			return new ResponseEntity(false, StatusCode.ERROR, "修改用户状态失败！");
		}
		return new ResponseEntity(true, StatusCode.OK, "修改用户状态成功！");
	}

	/**
	 * 根据ID删除用户
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delUser")
	@ResponseBody
	public ResponseEntity delUserById(@RequestParam(value = "id") String id) {

		if (StringUtils.isBlank(id)) {
			return new ResponseEntity(false, StatusCode.ERROR, "没有可删除的用户！");
		}

		int result = userService.getBaseMapper().deleteById(id);
		if (result == 0) {
			return new ResponseEntity(false, StatusCode.ERROR, "删除用户失败，请检查日志！");
		}

		return new ResponseEntity(true, StatusCode.OK, "删除用户成功！");
	}

	/**
	 * 批量删除
	 * @return
	 */
	@RequestMapping(value = "/batchDelUser")
	@ResponseBody
	public ResponseEntity batchDelUser(@RequestParam(value = "ids") String ids) {
		System.out.println("=================ids: " + ids);
		if (StringUtils.isBlank(ids)) {
			return  new ResponseEntity(false, StatusCode.ERROR, "没有可删除的用户");
		}
		String[] arrayIds = ids.split(",");
		List<String> idList = new ArrayList<>();
		for (int i=0;i<arrayIds.length;i++) {
			idList.add(arrayIds[i]);
		}
		int result = userService.getBaseMapper().deleteBatchIds(idList);
		if (result == 0) {
			return  new ResponseEntity(false, StatusCode.ERROR, "批量删除用户失败，请检查日志！");
		}
		return new ResponseEntity(true, StatusCode.OK, "批量删除用户成功");
	}

	/**
	 * 清空所有记录
	 * @return
	 */
	@RequestMapping(value = "/btnDelAllUser")
	@ResponseBody
	public ResponseEntity delAllUser() {
		int result = userService.getBaseMapper().delete(new QueryWrapper<TbUser>().isNotNull("id"));
		if (result == 0) {
			return  new ResponseEntity(false, StatusCode.ERROR, "清空所有数据失败，请检查日志！");
		}
		return new ResponseEntity(true, StatusCode.OK, "数据已全部清空！");
	}

	/**
	 * 重置用户密码
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/resetPassword")
	@ResponseBody
	public ResponseEntity resetPassword(@RequestParam(value = "id") String id) {
		if (StringUtils.isBlank(id)) {
			return new ResponseEntity(false, StatusCode.ERROR, "没有可重置的用户！");
		}
		TbUser tbUser = new TbUser();
		tbUser.setId(Long.parseLong(id));
		String[] encrypt = EncryptUtil.encrypt("");
		tbUser.setPassword(encrypt[0]);// 重置密码
		tbUser.setSalt(encrypt[1]);// 重置盐
		int result = userService.getBaseMapper().updateById(tbUser);
		if (result == 0) {
			return new ResponseEntity(false, StatusCode.ERROR, "重置用户密码失败！");
		}
		return new ResponseEntity(true, StatusCode.OK, "重置用户密码成功！");
	}

	/**
	 * 获取用户信息
	 * @return
	 */
	@GetMapping("/userInfo")
	@ResponseBody
	public ResponseEntity getUser(HttpSession session) {
		System.out.println("=============== 获取用户信息 ==============");
		System.out.println(session.getAttribute("user"));
		System.out.println("=============== 获取用户信息 ==============");
		TbUser user = (TbUser) session.getAttribute("user");
		if (user == null) {
			return new ResponseEntity(false, StatusCode.ERROR, "获取用户信息失败，请重新登录！");
		}
		return new ResponseEntity(true, StatusCode.OK, "获取用户信息成功", user);
	}
}

